package online.sixfish.doubao.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import online.sixfish.doubao.enumration.CommonConstant;
import online.sixfish.doubao.mapper.NoticeMapper;
import online.sixfish.doubao.model.dto.AddNoticeDTO;
import online.sixfish.doubao.model.dto.PageDTO;
import online.sixfish.doubao.model.dto.QueryNoticeDTO;
import online.sixfish.doubao.model.entity.Notice;
import online.sixfish.doubao.service.admin.AdminNoticeService;
import online.sixfish.common.utils.SecurityUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class AdminNoticeServiceImpl implements AdminNoticeService {
    @Resource
    NoticeMapper noticeMapper;
    @Override
    public void addNotice(AddNoticeDTO addNoticeDTO) {
        insertNotice(addNoticeDTO);
    }

    @Override
    public PageDTO listNotice(QueryNoticeDTO queryNoticeDTO) {
        Page<Notice> page = new Page<>(queryNoticeDTO.getPageNum(), queryNoticeDTO.getPageSize());
        QueryWrapper<Notice> wrapper = new QueryWrapper<>();

        if(Objects.nonNull(queryNoticeDTO.getType())){
            wrapper.eq("type",queryNoticeDTO.getType());
        }
        if(Objects.nonNull(queryNoticeDTO.getStatus())){
            wrapper.eq("status",queryNoticeDTO.getStatus());
        }
        if(StringUtils.isNotBlank(queryNoticeDTO.getTitle())){
            wrapper.like("title",queryNoticeDTO.getTitle());
        }
        wrapper.orderByDesc("create_time");
        wrapper.ne("status", CommonConstant.SYS_ILLEGAL_STATUS);
        Page<Notice> noticePage = noticeMapper.selectPage(page, wrapper);
        return PageDTO.build(noticePage);
    }

    @Override
    public void updateNotice(Notice notice) {
        notice.setPublisherId(null);
        notice.setStatus(null);
        notice.setCreateTime(null);
        notice.setUpdateTime(null);
        noticeMapper.updateById(notice);

    }

    private void insertNotice(AddNoticeDTO addNoticeDTO) {
        Notice notice = new Notice();
        BeanUtils.copyProperties(addNoticeDTO,notice);
        notice.setPublisherId(SecurityUtil.currentUserId());
        noticeMapper.insert(notice);
    }
}
